package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.CarFile;
import com.ruoyi.system.service.ICarFileService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;


/**
 * 车辆文件Controller
 *
 * @author ruoyi
 * @date 2022-03-13
 */
@Controller
@RequestMapping("/system/file")
public class CarFileController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CarFileController.class);
    private String prefix = "system/file";
    @Autowired
    private ICarFileService carFileService;

    @RequiresPermissions("system:file:view")
    @GetMapping()
    public String file() {
        return prefix + "/file";
    }

    /**
     * 查询车辆文件列表
     */
    @RequiresPermissions("system:file:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CarFile carFile) {
        startPage();
        List<CarFile> list = carFileService.selectCarFileList(carFile);
        return getDataTable(list);
    }
    /**
     * 查询车辆文件列表
     */
    @RequiresPermissions("system:file:list")
    @PostMapping("/listByBusType")
    @ResponseBody
    public AjaxResult listByBusType(CarFile carFile) {
        List<CarFile> list = carFileService.getFiles(carFile.getBusId(),carFile.getBusType(),carFile.getGroupType());
        return success(list);
    }

    /**
     * 导出车辆文件列表
     */
    @RequiresPermissions("system:file:export")
    @Log(title = "车辆文件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CarFile carFile) {
        List<CarFile> list = carFileService.selectCarFileList(carFile);
        ExcelUtil<CarFile> util = new ExcelUtil<CarFile>(CarFile.class);
        return util.exportExcel(list, "车辆文件数据");
    }

    /**
     * 新增车辆文件
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存车辆文件
     */
    @RequiresPermissions("system:file:add")
    @Log(title = "车辆文件", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CarFile carFile) {
        return toAjax(carFileService.insertCarFile(carFile));
    }

    /**
     * 修改车辆文件
     */
    @RequiresPermissions("system:file:edit")
    @GetMapping("/edit/{fileId}")
    public String edit(@PathVariable("fileId") Long fileId, ModelMap mmap) {
        CarFile carFile = carFileService.selectCarFileByFileId(fileId);
        mmap.put("carFile", carFile);
        return prefix + "/edit";
    }

    /**
     * 修改保存车辆文件
     */
    @RequiresPermissions("system:file:edit")
    @Log(title = "车辆文件", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CarFile carFile) {
        return toAjax(carFileService.updateCarFile(carFile));
    }
    @RequiresPermissions("system:file:edit")
    @Log(title = "车辆文件", businessType = BusinessType.UPDATE)
    @PostMapping("/editGroupType")
    @ResponseBody
    public AjaxResult editGroupType(CarFile carFile) {
        return toAjax(carFileService.updateCarFile(carFile));
    }
    /**
     * 删除车辆文件
     */
    @RequiresPermissions("system:file:remove")
    @Log(title = "车辆文件", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(carFileService.deleteCarFileByFileIds(ids));
    }


    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files, @RequestParam("busId") Long busId, @RequestParam("fileType") String fileType, @RequestParam("busType") String busType, @RequestParam(value = "groupType", required = false, defaultValue = "0") String groupType) throws Exception {
        try {
            log.info("业务id={}", busId);
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            List<CarFile> carFiles = new LinkedList<>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
//                String url = serverConfig.getUrl() + fileName;
//                fileName = org.apache.commons.lang3.StringUtils.substringAfter(fileName, Constants.RESOURCE_PREFIX);
                carFileService.yasuo(RuoYiConfig.getProfile() + fileName);
                String url = RuoYiConfig.getPreFileUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
                CarFile carFile = new CarFile();
                carFile.setFileUrl(fileName);
                carFile.setFileName(file.getOriginalFilename());
                carFile.setBusId(busId);
                carFile.setFileType(fileType);
                carFile.setBusType(busType);
                carFile.setGroupType(groupType);
                carFile.setCreateBy(getLoginName());
                carFile.setCreateTime(new Date());
                carFile.setUpdateBy(carFile.getCreateBy());
                carFile.setUpdateTime(carFile.getCreateTime());
                carFileService.insertCarFile(carFile);
                carFile.setFileUrl(url);
                carFiles.add(carFile);
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            ajax.put("files", carFiles);
            return success(carFiles);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    private static final String FILE_DELIMETER = ",";
}
